<!--
  Bim 模拟弹窗
-->
<template>
  <a-modal
          title="BIM模拟"
          width="90%"
          v-model="visible"
          :maskClosable="false"
          @cancel="closeBim"
          :footer="null">
    <div style="height: 50vh;position: relative">
      <div v-if="state.loading" class="layout-loading-process">
        <a-progress type="circle" :percent="state.percent" />
      </div>
      <canvas id="BimCanvas"></canvas>
    </div>
    <div class="setting">
     <div style="width: 210px;margin-right: 15px">
      <div style="display: flex;justify-content: space-between;margin-bottom: 5px">
        <a-button @click="reset" style="width: 100px">重置</a-button>
        <a-button @click="onPlay" style="width: 100px">播放</a-button>
      </div>
       <div style="display: flex;justify-content: space-between;align-items: center">
         <a-date-picker style="width: 136px" v-model="form.startDate" value-format="YYYY-MM-DD" format="YYYY-MM-DD" @change="changeTime" />
         <a-button @click="settingShow = true">设置</a-button>
       </div>
     </div>
      <div style="flex: 1">
        <a-slider v-model="form.percent" :max="form.max"  disabled />
        <div style="margin-top: 15px">{{ form.currentDate }}</div>
      </div>
    </div>
    <div class="setting-config" v-show="settingShow">
      <a-row>
        <a-col :span="8">
          <div class="title">【开始/结束日期】</div>
          <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
            <a-form-model-item label="开始日期">
              <a-date-picker v-model="settingForm.startDate" value-format="YYYY-MM-DD" format="YYYY-MM-DD"  />
            </a-form-model-item>
            <a-form-model-item label="结束日期">
              <a-date-picker  v-model="settingForm.endDate" value-format="YYYY-MM-DD" format="YYYY-MM-DD"  />
            </a-form-model-item>
          </a-form-model>
        </a-col>
        <a-col :span="8">
          <div class="title">【默认每天对应时间】</div>
          <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
            <a-form-model-item label="">
              <a-select v-model="settingForm.everyTime">
                <a-select-option :value="0.5">0.5s</a-select-option>
                <a-select-option :value="1">1s</a-select-option>
                <a-select-option :value="2">2s</a-select-option>
                <a-select-option :value="3">3s</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-col>
        <a-col :span="8">
          <div class="title">【模拟时间基准】</div>
          <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
            <a-form-model-item label="">
              <a-radio-group v-model="settingForm.mockType">
                <a-radio :style="radioStyle" :value="1">
                  按计划时间模拟
                </a-radio>
                <a-radio :style="radioStyle" :value="2">
                  按实际时间模拟
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
      <div style="text-align: right">
        <a-button style="margin-right: 10px" @click="settingShow=false">取消</a-button>
        <a-button type="primary" @click="confirmBtn">确定</a-button>
      </div>
    </div>
    <div class="alert-area">
      <div class="cell" style="font-size: 18px">计划进度</div>
      <div class="cell" v-for="item in alertList" :key="item.className">
        <span>{{ item.name }}</span>
        <div class="color-block bc-1" :class="item.className"></div>
      </div>
      <div class="cell" style="font-size: 20px">{{ time }}</div>
    </div>
  </a-modal>
</template>

<script>
  import { getBimProjectMasterModelList } from '@/api/bimIntegrate/bimModel' // BIM模型关联
  import moment from 'moment'
  import { Slider } from 'ant-design-vue'
  import { validateToken } from '@/api/bimIntegrate/request'
  import { modelConfig } from '@/components/BimIntegrate/websiteConfig'
  import new_front_chinese from '@/components/BimIntegrate/resource/front_chinese.png'
  import new_back_chinese from '@/components/BimIntegrate/resource/back_chinese.png'
  import new_top_chinese from '@/components/BimIntegrate/resource/top_chinese.png'
  import new_bottom_chinese from '@/components/BimIntegrate/resource/bottom_chinese.png'
  import new_left_chinese from '@/components/BimIntegrate/resource/left_chinese.png'
  import new_right_chinese from '@/components/BimIntegrate/resource/right_chinese.png'
  import new_compass_plate_chinese from '@/components/BimIntegrate/resource/compass_chinese.png'

  const FLOOR_TREE = 'FLOOR_TREE'
  const DOMAIN_TREE = 'DOMAIN_TREE'

  const WINDData = window.WIND && window.WIND.WINDData
  const WINDView = window.WIND && window.WIND.WINDView
  export default {
    name: 'BimImitateDialog',
    props: {
      modelList: {
        type: Array,
        default() {
          return []
        }
      }
    },
    components: {
      ASlider: Slider
    },
    data() {
      return {
        settingShow: false,
        radioStyle: {
          display: 'block',
          height: '30px',
          lineHeight: '30px',
        },
        form: {
          startDate: moment().format('YYYY-MM-DD'),
          currentDate: moment().format('YYYY-MM-DD'),
          endDate: '',
          everyTime: 0.5,
          mockType: 1,
          percent: 0,
          max: 100
        },
        settingForm: {
          startDate: moment().format('YYYY-MM-DD'),
          currentDate: '',
          endDate: '',
          everyTime: 0.5,
          mockType: 1,
        },
        alertList: [
          {
            name: '未开始',
            className: 'bc-1'
          },
          // {
          //   name: '未开始(延期)',
          //   className: 'bc-2'
          // },
          {
            name: '执行中',
            className: 'bc-3'
          },
          // {
          //   name: '执行中(延期)',
          //   className: 'bc-4'
          // },
          {
            name: '已完成',
            className: 'bc-5'
          },
          {
            name: '已完成(提前)',
            className: 'bc-6'
          },
          {
            name: '已完成(延期)',
            className: 'bc-7'
          }
        ],
        visible: true,
        state: {
          loading: false,
          percent: 0, // 模型加载百分比
          currentData: null, // 当前模型的数据对象
          currentView: null, // 当前模型的视图对象
          floors: null, // 楼层数据
          domains: null, // 专业数据
          selectedFloors: null,
          selectedDomains: null,
          entities: [], // 所选中的实体
          roamSpeed: 4, // 漫游速度
          setParms: {} // 光照、背景等相关设置属性的对象集合
        },
        // 批量上色id集合
        batchColorIds: {
          bc1: [],
          // bc2: [],
          bc3: [],
          // bc4: [],
          bc5: [],
          bc6: [],
          bc7: [],
          bc8: [],
        },
        time: moment().format('YYYY-MM-DD HH:mm:ss'),
        timer: null,
        isModelParameterLoaded: false,
        playList: [],
        needPlayList: [],
        showBimIds: []
      }
    },
    async mounted() {
      if (!sessionStorage.getItem('bimToken')) {
        await validateToken()
      }
      this.getBimProjectMasterModelList()
      this.$nextTick(() => {
        this.initBim()
      })
    },
    methods: {
      changeTime(value) {
        this.form.currentDate = value
        this.form.startDate = value
        this.settingForm.startDate = value
        this.reset()
        this.setNeedPlayList()
      },
      getBimProjectMasterModelList() {
        const { planId } = this.$route.query
        let data = {
          projectMasterId: planId,
          modelId: this.modelList[0].id
        }
        getBimProjectMasterModelList(data).then(res=>{
          this.playList = res.data
          this.setNeedPlayList()
        })
      },
      setNeedPlayList() {
        let arr = []
        this.playList.forEach(item=>{
          if(this.form.endDate) {
            if(moment(item.dayDate).isBetween(this.form.startDate, this.form.endDate, 'days')) {
              arr.push(item)
            }
          }
          else if(moment(item.dayDate).isSameOrAfter(this.form.startDate, 'days')) {
            arr.push(item)
          }
        })
        this.needPlayList = arr
        this.form.max = this.needPlayList.length
      },
      closeBim() {
        this.reset()
        this.$emit("closeBim")
      },
      // 点击播放
      onPlay() {
        const { currentView, currentData } = this.state
        const WINDViewControl =  currentView.getWINDViewControl()
        if(!this.isModelParameterLoaded) {
          this.$message.warning('模型数据未加载完毕,请稍后')
          return
        }
        if(this.needPlayList.length === 0) {
          this.$message.warning('当前时间没有数据')
          return
        }
        let delay = this.form.everyTime * 1000
        let idx = -1 // 设置索引 从-1开始
        //隐藏构建树
        WINDViewControl.hideTreeRoot(this.state.domains[0])
        // WINDViewControl.hideEachComponents()
        this.showBimIds = []

        this.timer = setInterval(()=>{
          idx++;
          this.form.percent++;
          this.form.currentDate = this.needPlayList[idx].dayDate
          let nodeList = this.needPlayList[idx].nodeList
          console.log('节点数据', nodeList)
          if(nodeList.length>0) {
            let bimIds = nodeList[0].bimId.split(',')
            // let bimIds = []
            // nodeList.forEach(item => {
            //    const bimId = item.bimId.split('&&&&')[1]
            //    bimIds.push(bimId)
            // })
            console.log(bimIds, 'bimIds')
            bimIds.forEach(item=>{
              if(!this.showBimIds.includes(item)) {
                console.log(item, 'bimId')
                WINDViewControl.showAssignedEntities(item)
                this.showBimIds.push(item)
              }
            })
          }
          console.log('显示节点', this.showBimIds)
          this.setBatchColorIds()
          this.setColors()
        }, delay)
      },
      setBatchColorIds() {
        this.batchColorIds = {
          bc1: [],
          // bc2: [],
          bc3: [],
          // bc4: [],
          bc5: [],
          bc6: [],
          bc7: [],
          bc8: [],
        }
        let arr = [];
        this.needPlayList.forEach(item => {
          if(moment(item.dayDate).isBefore(this.form.currentDate, 'days')) {
            arr.push(item)
          }
        })
        arr.forEach(item => {
          item.nodeList.forEach(ele => {
            // const uuid = ele.bimId.split('&&&&')[1]
            const uuid = ele.bimId
            // 按照计划时间模拟
            if(this.form.mockType === 1) {
              if(moment(this.form.currentDate).isBefore(ele.startDate, 'days')) {
                // 未开始
                if(!this.batchColorIds.bc1.includes(uuid)) {
                  this.batchColorIds.bc1 = uuid.split(',')
                }
              } else if(moment(this.form.currentDate).isBetween(ele.startDate, ele.endDate, 'days')) {
                // 执行中
                if(!this.batchColorIds.bc3.includes(uuid)) {
                  // this.batchColorIds.bc3.push(uuid)
                  this.batchColorIds.bc3 = uuid.split(',')
                }
              } else if(moment(this.form.currentDate).isSameOrAfter(ele.endDate, 'days')) {
                //已完成
                if(!this.batchColorIds.bc5.includes(uuid)) {
                  // this.batchColorIds.bc5.push(uuid)
                  this.batchColorIds.bc5 = uuid.split(',')
                }
              }
            } else {
              const isBefore = moment(ele.completeDate).isBefore(ele.endDate, 'days')
              const isSame = moment(ele.completeDate).isSame(ele.endDate, 'days')
              // 按照实际时间模拟
              if(moment(this.form.currentDate).isBefore(ele.startDate, 'days')) {
                // 未开始
                if(!this.batchColorIds.bc1.includes(uuid)) {
                  // this.batchColorIds.bc1.push(uuid)
                  this.batchColorIds.bc1 = uuid.split(',')
                }
              } else if(isBefore&&(moment(this.form.currentDate).isBefore(ele.completeDate, 'days'))) {
                // 执行中
                if(!this.batchColorIds.bc3.includes(uuid)) {
                  // this.batchColorIds.bc3.push(uuid)
                  this.batchColorIds.bc3 = uuid.split(',')
                }
              } else if(!isBefore&&(moment(this.form.currentDate).isBefore(ele.endDate, 'days'))) {
                // 执行中
                if(!this.batchColorIds.bc3.includes(uuid)) {
                  // this.batchColorIds.bc3.push(uuid)
                  this.batchColorIds.bc3 = uuid.split(',')
                }
              } else if(isSame&&(moment(this.form.currentDate).isSame(ele.completeDate, 'days'))) {
                //已完成
                if(!this.batchColorIds.bc5.includes(uuid)) {
                  // this.batchColorIds.bc5.push(uuid)
                  this.batchColorIds.bc5 = uuid.split(',')
                }
              } else if(isBefore&&(moment(this.form.currentDate).isSameOrAfter(ele.completeDate, 'days'))) {
                //已完成提前
                if(!this.batchColorIds.bc6.includes(uuid)) {
                  // this.batchColorIds.bc6.push(uuid)
                  this.batchColorIds.bc6 = uuid.split(',')
                }
              }
              else if(!isBefore&&(moment(this.form.currentDate).isSameOrAfter(ele.endDate, 'days'))) {
                //已完成延期
                if(!this.batchColorIds.bc7.includes(uuid)) {
                  // this.batchColorIds.bc7.push(uuid)
                  this.batchColorIds.bc7 = uuid.split(',')
                }
              }
            }
          })
        })
      console.log(this.batchColorIds, ' this.batchColorIds')
      },
      setColors() {
        const { currentView } = this.state
        const WINDViewControl =  currentView.getWINDViewControl()
        // 创建一个批量集合,可以批量操作实体
        WINDViewControl.createBatchEntities(1, this.batchColorIds.bc1)
        WINDViewControl.createBatchEntities(3, this.batchColorIds.bc3)
        WINDViewControl.createBatchEntities(5, this.batchColorIds.bc5)
        WINDViewControl.createBatchEntities(6, this.batchColorIds.bc6)
        WINDViewControl.createBatchEntities(7, this.batchColorIds.bc7)
        // 给每个状态设置颜色
        WINDViewControl.coloringBatchEntities(1,102, 102, 102,255)
        WINDViewControl.coloringBatchEntities(3,0, 204, 102,255)
        WINDViewControl.coloringBatchEntities(5,0, 153, 255,255)
        WINDViewControl.coloringBatchEntities(6,204, 204, 0,255)
        WINDViewControl.coloringBatchEntities(7,255, 153, 255,255)
      },
      initBim() {
        this.isModelParameterLoaded = false
        let data, view, config
        let floorTree = { YZTreeType: FLOOR_TREE, id: 0 }
        let domainTree = { YZTreeType: DOMAIN_TREE, id: 1 }
        // 模型服务器设置
        config = Object.assign({}, modelConfig)
        let canvas = document.querySelector('#BimCanvas')
        // WINDData初始化
        data = new WINDData(config)
        // WINDView初始化
        view = new WINDView(canvas)
        //设置控制树显示规则类型
        //let floorTypes = [window.WIND.TreeRuleType.PROJECT_NAME, window.WIND.TreeRuleType.STOREY_NAME]
        //let domainTypes = [window.WIND.TreeRuleType.DOMAIN_NAME, window.WIND.TreeRuleType.CATEGORY_NAME, window.WIND.TreeRuleType.TYPE_NAME, window.WIND.TreeRuleType.COMPONENT_UNIQUEID]
        // 创建构件显示控制树 这里需要创建树 不然无法添加颜色 颜色使用id渲染 高亮是uuid
        // view.getWINDViewControl().createComponentTree(floorTypes, floorTree)
        // view.getWINDViewControl().createComponentTree(domainTypes, domainTree)
        view.bindWINDData(data)

        //设置模型视图背景颜色 rgb(194 191 217)
        let color = [194, 191, 217, 255]
        view.getWINDViewSetting().setBackgroundPureColor(color[0], color[1], color[2], color[3])
        //设置导航辅助六个面显示的图片
        view.getWINDViewAssist().setNavigateResource(new_front_chinese, new_back_chinese, new_top_chinese, new_bottom_chinese, new_left_chinese, new_right_chinese, new_compass_plate_chinese)
        //开启导航辅助
        view.getWINDViewAssist().setNavigateProperty(20, 0, 120)
        view.getWINDViewAssist().openNavigateAssist()
        // view.getWINDViewSetting().isWireframeOpened(false)
        // view.getWINDViewSetting().isLightShadowOpened(false)
        view.getWINDViewSetting().isRealModeOpened(false)
        // 数据加载执行回调
        data.addWINDDataCallback(1, (type, option) => {
          this.updateDataNode(type, option)
        })
        this.$nextTick(() => {
          this.state = {
            ...this.state,
            currentData: data,
            currentView: view,
            floors: [floorTree],
            domains: [domainTree]
          }
        })
        this.openModelData(data, view)
      },
      // 打开模型
      async openModelData(data, view) {
        let modelData = {
          modelId: this.modelList[0].modelFileId,
          version: this.modelList[0].modelFileVersion
        }
        await data.getWINDDataLoader().openModelData(modelData.modelId, modelData.version)
        await data.getWINDDataLoader().openModelParameter() //打开模型属性
        this.isModelParameterLoaded = true
      },
      /**
       * 设置state里数据
       */
      setState(state, fn) {
        this.state = {
          ...this.state,
          ...state
        }
        if (fn) {
          this.$nextTick(() => {
            fn()
          })
        }
      },
      // 数据回调之后, 更新进度条
      updateDataNode(type, value) {
        if (isNaN(value)) {
          this.setState({
            loading: false,
            percent: 0
          })
          this.$message.warning('模型文件异常')
          return
        }
        if (type === 1 || type === window.WIND.CallbackType.DATALOAD_GEOMETRY_CHANGED) {
          // 模型加载百分比回调
          let percentNum = Math.min(100, Math.max(0, Math.floor(value))) || 0
          if (percentNum >= 0 && percentNum < 100) {
            this.setState({
              loading: true,
              percent: percentNum
            })
          } else {
            this.setState({
              loading: false
            })
          }
        }
      },
      // 重置
      reset() {
        if(!this.isModelParameterLoaded) {
          this.$message.warning('模型数据未加载完毕,请稍后')
          return
        }
        this.form.percent = 0
        if(this.timer) {
          console.log('清除定时器')
          clearInterval(this.timer)
        }
        const { currentView } = this.state
        const WINDViewControl =  currentView.getWINDViewControl()
        WINDViewControl.showEachComponents()
        WINDViewControl.discoloringBatchEntities(1)
        WINDViewControl.discoloringBatchEntities(3)
        WINDViewControl.discoloringBatchEntities(5)
        WINDViewControl.discoloringBatchEntities(6)
        WINDViewControl.discoloringBatchEntities(7)
      },
      confirmBtn() {
        this.form = {
          ...this.form,
          ...this.settingForm,
          currentDate: this.settingForm.startDate
        }
        this.settingShow = false
        this.reset()
        this.setNeedPlayList()
      },
    },
    destroyed() {
      this.reset()
    }
  }
</script>

<style scoped lang="less">
  #BimCanvas {
    height: 100%;
    width: 100%;
  }

  .layout-loading-process {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 10%;
    height: 10%;
    transform: translate(-50%, -50%);
    z-index: 98;
  }

  .alert-area {
    position: absolute;
    top: 79px;
    left: 24px;
    width: 190px;

    .cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #fff;
      font-size: 16px;
      margin-bottom: 2px;

      .color-block {
        width: 60px;
        height: 20px;
      }
    }

    .bc-1 {
      background-color: rgb(102, 102, 102);
    }

    .bc-2 {
      background-color: rgb(255, 179, 179);
    }

    .bc-3 {
      background-color: rgb(0, 204, 102);
    }

    .bc-4 {
      background-color: rgb(255, 0, 0);
    }

    .bc-5 {
      background-color: rgb(0, 153, 255);
    }

    .bc-6 {
      background-color: rgb(204, 204, 0);
    }

    .bc-7 {
      background-color: rgb(255, 153, 255);
    }
  }
  .setting {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    width: 100%;
  }
  .setting-config {
    width: 100%;
    min-height: 100px;
    box-sizing: border-box;
    border: 1px dashed #666;
    padding: 15px;
    margin-top: 10px;
  }
  ::v-deep .ant-form-item .ant-form-item-label {
    width: 80px;
  }
  ::v-deep .ant-form-item {
    margin-bottom: 0;
  }
</style>